package mywebapps.web;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mywebapps.dao.ArtProductDao;
import mywebapps.dao.hibernate.ArtProductDaoImpl;
import mywebapps.model.ArtProduct;

public class ImageServlet extends HttpServlet {
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
	        throws ServletException, IOException {
	    String imageName = req.getPathInfo().substring(1);
	    byte[] image = getImage(imageName);
	    
	    resp.setHeader("Content-Type", "image/jpg");
	    resp.setHeader("Content-Length", String.valueOf(image.length));
	    
	    Calendar inOneMonth = Calendar.getInstance();
	    inOneMonth.add(Calendar.MONTH, 1);
	    resp.setDateHeader("Expires", inOneMonth.getTimeInMillis());
	    resp.getOutputStream().write(image);
	}
	
	public byte[] getImage(String name) {
		Map<String, byte[]> cachedImagesMap 
		    = (Map<String, byte[]>) getServletContext().getAttribute(this.getClass().getName());
		
		if(cachedImagesMap == null) {
			synchronized(this) {
				if(cachedImagesMap == null) {
					cachedImagesMap = new HashMap<String, byte[]>();
				}
			}
		}
		
		byte[] image = cachedImagesMap.get(name);
		if(image == null) {
			ArtProductDao artProductDao = new ArtProductDaoImpl();
			ArtProduct prod = artProductDao.getArtProductByName(name);
			image = prod.getImage();
			cachedImagesMap.put(name, image);
		}
		return image;
	}
}
